package com.fang.security.security.handler;

import com.alibaba.fastjson.JSON;
import com.fang.security.common.CommonConstants;
import com.fang.security.common.exception.RException;
import com.fang.security.common.result.JsonResult;
import com.fang.security.entity.DO.SysUser;
import com.fang.security.service.SysUserService;
import com.fang.security.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 登录成功处理器
 * @Author Bernie
 * @Date 2024/4/23 10:45
 **/
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        SysUser sysUser = sysUserService.selectByName(userDetails.getUsername());
//        sysUser.setLastLoginTime(new Date());
//        sysUser.setUpdateTime(new Date());
//        sysUser.setUpdateUser(sysUser.getId());
//        sysUserService.update(sysUser);

        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展

        String token = null;
        try {
            token = JWTUtil.signToToken(sysUser.getUsername(), sysUser.getUserId());
        } catch (RException e) {
            JsonResult result = JsonResult.fail(e);
            httpServletResponse.setContentType(CommonConstants.CommonResponse.JSON_U8_CONTENT_TYPE);
            httpServletResponse.getWriter().write(JSON.toJSONString(result));
        }

        //返回json数据
        JsonResult result = JsonResult.success(token);
        httpServletResponse.setContentType(CommonConstants.CommonResponse.JSON_U8_CONTENT_TYPE);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
